const Koa = require("koa");
const app = new Koa();
const schedule = require('node-schedule')
const moment = require('moment')

const { createServer } = require("http")
const httpServer = createServer(app.callback())

const ws = require('./ws/ws')
const http = require('./http/http')
const logger = require("./utils/logger")
const config = require("./config")
const { shengchengShangbanSta } = require("./ws/kaoqin");
const mysqlUtil = require("./utils/mysqlUtil");
const { autoPaiban } = require("./ws/xingzheng");

ws.initWs(httpServer)
http.initHttp(app)

logger.info('node env', process.env.NODE_ENV)

httpServer.listen(config.port, async () => {
    logger.info('server start success 329', process.pid)

    await shengchengShangbanSta()
    // 每天凌晨触发的定时器
    schedule.scheduleJob('0 0 0 * * *', async () => {
        try {
            // 更新考勤信息 
            await shengchengShangbanSta()
            // 发送值班通知
            let next3Day = moment().add(3, 'day').format('YYYY-MM-DD')
            let res = await mysqlUtil.execute('SELECT * FROM con_jiejiari WHERE riqi = ? LIMIT 1', [next3Day])
            if (res.length == 0) return
    
            let zhiban = res[0].zhiban
            if (zhiban == null) return
    
            for (let i = 0; i != zhiban.length; i++) {
                // 插入通知
                await mysqlUtil.execute('INSERT INTO tb_user_notification SET ?', [{
                    uid: zhiban[i].uid, // 请假人的uid
                    typ: 22,
                    title: '排班安排',
                    content: '管理员安排你在' + next3Day + '日进行值班，请提前做好安排',
                    sta: 0,
                    resTyp: 3,
                    relevenceId: res[0].id,
                    createTime: Date.now()
                }])
            }
        } catch (err) {
            logger.error('定时器错误', err)
        }
    })

    // 每月21号进行自动排班
    schedule.scheduleJob('0 0 0 21 * *', async () => {
        try {
            autoPaiban({}, {uid: 111}, {})
        } catch (err) {
            logger.error('定时器错误', err)
        }
    })
})
